package com.rc.saas.tenant.job;


import com.rc.saas.tenant.common.redis.RedisLoader;
import com.rc.saas.tenant.common.task.PlatformTaskEnum;
import com.rc.saas.tenant.model.task.PlatformTaskSetting;
import com.rc.saas.tenant.service.task.PlatformTaskSettingService;
import com.rc.saas.tenant.service.ticket.TenantTicketScheduleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author frog
 * @date 2021/03/09
 */
public class TicketTask {

    Logger logger = LoggerFactory.getLogger(TicketTask.class);

    @Autowired
    private TenantTicketScheduleService tenantTicketScheduleService;

    @Autowired
    private PlatformTaskSettingService platformTaskSettingService;

    @Autowired
    private RedisLoader redisLoader;

    //发送优惠券
    public void run() {
        try {
            Object o = redisLoader.get(PlatformTaskEnum.SEND_TICKET_TASK.getCode());
            if (o == null) {
                //加锁 10秒过期
                redisLoader.set(PlatformTaskEnum.SEND_TICKET_TASK.getCode(), "1", 10000L);
            } else {
                logger.info("定时发送优惠券功能已经在执行!!,不能重复执行");
                return;
            }

            //是否开启执行
            PlatformTaskSetting platformTaskSetting = platformTaskSettingService.selectByTaskType(PlatformTaskEnum.SEND_TICKET_TASK.getCode());
            if (platformTaskSetting == null) {
                logger.info("定时发送优惠券功能暂停使用!");
                return;
            }

            tenantTicketScheduleService.ticketTask();

            //删锁
            redisLoader.delete(PlatformTaskEnum.SEND_TICKET_TASK.getCode());

            logger.info("成功赠送优惠券[定时发送优惠券]");
        } catch (Exception e) {
            logger.error("发送优惠券失败[定时发送优惠券]", e);
        }
    }
}
